#! /bin/bash

TEST_OUT_PATH="/home/ayash/Desktop/ex3_test_file.txt"
NUM_WRITES=10

clear

if [ -e $TEST_OUT_PATH ]
then
	rm $TEST_OUT_PATH
fi


# compile without debug mode
make clean all > /dev/null
if [ $?  != 0 ]
then		
	echo "Error: compilation failed!"
	exit 1
fi



#run the test with valgrind 
valgrind ./a.out $TEST_OUT_PATH $NUM_WRITES 2> /dev/null

if [ $?  != 0 ]
then		
	echo "Error: valgrind return value is != 0"
	echo "use the comman: valgrind ./a.out $TEST_OUT_PATH $NUM_WRITES"
	
	echo
	echo 
	echo "Output file:" 
	echo "--------------------------------" 
	echo
	cat $TEST_OUT_PATH
	
	exit 2
fi


# test in debug mode

if [ -e $TEST_OUT_PATH ]
then
	rm $TEST_OUT_PATH
fi

# compile with debug mode
make clean all DBG=1 > /dev/null
if [ $?  != 0 ]
then		
	echo "Error: compilation failed!"
	exit 2
fi


# run the test
./a.out $TEST_OUT_PATH $NUM_WRITES > ./log.txt
if [ $?  != 0 ]
then		
	echo "Error: return value of the test != 0"
	exit 3
fi

echo 
echo

if [ -e $TEST_OUT_PATH ]
then
	echo "Showing the output of the test"
	echo "--------------------------------" 
	echo

	cat $TEST_OUT_PATH

else
	echo "Error: no output file was created in the path: $TEST_OUT_PATH"	

fi

echo 
echo "show the log file?: y/n"
read answer

if [ "$answer" == "y" ]
then
	cat ./log.txt
fi


cat $TEST_OUT_PATH | grep "thread1: this is my first line" | wc -l > tmp_file
read answer < tmp_file
if [ $answer != $NUM_WRITES ]
then
	echo "Test Failed!"
	exit 4
fi 

cat $TEST_OUT_PATH | grep "thread2: this is my first line" | wc -l > tmp_file
read answer < tmp_file
if [ $answer != $NUM_WRITES ]
then
	echo "Test Failed!"
	exit 5
fi 
rm tmp_file

echo
echo
echo "Test Passed"





